package com.um.springcloud.dubbo.cluster.persistence;

import cn.hutool.core.util.StrUtil;
import com.um.springcloud.dubbo.cluster.DeviceClusterPersistence;
import com.um.springcloud.dubbo.cluster.DeviceClusterProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * jdbc持久化
 *
 * @author 甘天伟
 * @since 2024/1/25
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
@ConditionalOnProperty(value = "hsh.device-cluster.persistence", havingValue = "jdbc")
public class JdbcPersistence implements DeviceClusterPersistence {

    @Autowired
    DeviceClusterProperties properties;

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 获取设备的服务端点
     *
     * @param key 设备码
     * @return 服务端点
     */
    @Override
    public String getDeviceEndpoint(String key) {
        String sql = StrUtil.format("SELECT {} FROM {} WHERE {} = ? limit 1",
                properties.getJdbcEndpointColumn(), properties.getJdbcTableName(), properties.getJdbcKeyColumn());

        try {
            return jdbcTemplate.queryForObject(sql, String.class, key);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 设置设备的服务端点
     *
     * @param key      设备码
     * @param endpoint 服务端点
     */
    @Override
    public void setDeviceEndpoint(String key, String endpoint) {
        String sql = StrUtil.format("UPDATE {} SET {} = ? WHERE {} = ?",
                properties.getJdbcTableName(), properties.getJdbcEndpointColumn(), properties.getJdbcKeyColumn());

        log.debug("set endpoint {} for device {}", endpoint, key);
        jdbcTemplate.update(sql, key, endpoint);
    }

    /**
     * 移除设备的服务端点
     *
     * @param key 设备码
     */
    @Override
    public void removeDeviceEndpoint(String key) {
        String sql = StrUtil.format("UPDATE {} SET {} = NULL WHERE {} = ?",
                properties.getJdbcTableName(), properties.getJdbcEndpointColumn(), properties.getJdbcKeyColumn());

        log.debug("remove endpoint for device {}", key);
        jdbcTemplate.update(sql, key);
    }
}
